var key="";
function img_change() {
  $("#alert-info").css("display","block");   
  $.ajax({
    type:"GET",
    url:"http://7xj9tj.com1.z0.glb.clouddn.com/"+key+"?imageView2/1/w/200/h/200",
    complete:function (response,status) {
      if (status=="success") {
        $('#my_img').attr('src', "http://7xj9tj.com1.z0.glb.clouddn.com/"+key+"?imageView2/1/w/200/h/200");
        portrait = "http://7xj9tj.com1.z0.glb.clouddn.com/"+key;
        $("#alert-info").removeClass("alert-info");
        $("#alert-info").text("上传完毕,请保存.");
        $("#alert-info").addClass("alert-success");                                    
      }else{
        setTimeout("img_change()", 1000);
      };
    },
  });
};
var upload = function() {
  portrait_flag=true;
  var file=$("#portrait").val();
  if (file=="") {
    alert('请先点击 选择文件\n再点击 点此上传');
    return false;
  };
  key="";
  $.ajax({
    url:"/login/login_id/",
    type:"GET",
    headers: {
      'X-CSRFToken': Cookies.get("csrftoken"),
    },       
    success:function(result0){
      key = result0+"/"+Math.round(Math.random()*10000).toString()+'/portrait.png';
      $.ajax({
        url:'/uptoken/?'+"key="+key,
        type:"GET",
        headers: {
          'X-CSRFToken': Cookies.get("csrftoken"),
        },  
        contentType:"application/x-www-form-urlencoded",     
        success:function(result1){
          $('#key').val(key);
          $('#token').val(result1); 
          $("#upload_file").submit();
          img_change();
        }
      });
    }
  });
}



/*var select_subject=function(subject){
    subject_selected[subject] = !subject_selected[subject];
    if ($("#"+subject).hasClass('active')) {
        $("#"+subject).removeClass('active');
    } else {
        $("#"+subject).addClass('active');
    }
}*/

var show_form = function(num){
  console.log('show form');

  $("#teacher_form_1").css('display', 'none');
  $("#teacher_form_2").css('display', 'none');
  $("#teacher_form_3").css('display', 'none');
  // $("#teacher_form_"+num.toString()).css("display","block");
  $("#teacher_form_"+num.toString()).fadeIn('slow');

  num-=1
  $('.form-header > p.heading').css('display', 'none');
  // $('.form-header > p.heading:eq('+num.toString()+')').css('display', 'block');
  $('.form-header > p.heading:eq('+num.toString()+')').fadeIn('slow');

  // 页面滑到顶部
  $('body').animate({scrollTop:0}, 800);

  // 左边进度条 显示切换
  $('.form-nav-header').css('display', 'none');
  $('.form-nav-header:eq('+num.toString()+')').css('display', 'block');

  // 左边导航栏 显示切换
  $('.nav-list a').removeClass('active');
  $('.nav-list a:eq('+num.toString()+')').addClass('active');
}


var form1_next = function(){
  if(!$("#teacher_form_1").validate()) return false;
  submitBasicInfo();
  show_form(2);
};

var check_form2=function(){
  if(!$("#teacher_form_2").validate()) return false;
  var recommend=false;
  if ($("#recommend_no:checked").length==0) {
    recommend=true;
  }; 
  if(recommend){
    tmp=$('#olm_points').val()
    if(tmp == "" ){
      alert('保送生请填竞赛成绩');
      return false;
    }
  }
  else{
    tmp=$('#cee_points').val();
    if(tmp==""){
      alert("非保送生请填高考成绩");
      return false;
    }
  }
  return true;
};

var form2_next = function(){
  if(check_form2()==false) return;
  submitPersonalInfo();
  show_form(3);
};


var check_form3=function(){
  if(!$("#teacher_form_3").validate()) return false;
  if($("input[name=teach-grade]:checked").length==0){
    alert("至少选择一个教授年级");
    return false;
  }
  
  if($("input[name=subject]:checked").length==0){
    alert("至少选择一个教授科目");
    return false;
  }
  return true;
};



var upload = function() {
    portrait_flag=true;
    var file=$("#portrait").val();
    if (file=="") {
        alert('请先点击 选择文件 再 点此上传');
        return false;
    };
    key="";
    $.ajax({
        url:"/login/login_id/",
        type:"GET",
        headers: {
            'X-CSRFToken': Cookies.get("csrftoken"),
        },       
        success:function(result0){
            key = result0+"/"+Math.round(Math.random()*10000).toString()+'/portrait.png';
            $.ajax({
                url:'/uptoken/?'+"key="+key,
                type:"GET",
                headers: {
                    'X-CSRFToken': Cookies.get("csrftoken"),
                },  
                contentType:"application/x-www-form-urlencoded",     
                success:function(result1){
                    $('#key').val(key);
                    $('#token').val(result1); 
                    $("#upload_file").submit();
                    img_change();
                }
            });
        }
    });
};

var goback=function(){
	history.go(-1);
}

var remote_save=function(teacherChange){
	$.ajax({
    type: 'PATCH',
    url: '/teacher/rest/teacher/'+teacher_id+'/',
    headers: {
      'X-CSRFToken': Cookies.get("csrftoken"),
    },
    data: teacherChange,
    async: false,
    success: function(res1){
      alert("保存成功"); 
    },
    error:function (error) {
      alert("保存失败,请联系客服人员")
    }
  });
};

var submitBasicInfo=function(){
	var gender="F";
  if ($("#gender_F:checked").length==0) {
    gender="M";
  };
	var teacherChange={
		"name": $("#name").val(),
    "gender": gender, 
    "email":$("#email").val(),
    "address": $("#address").val(), 

    "school": $("#school").val(), 
    "major": $("#major").val(),
    "grade": $("#grade").val(),
    "student_number":$("#student_number").val(),
    "portrait":portrait,
    "qq":$("#qq").val(),
	};
	remote_save(teacherChange);
};


var submitPersonalInfo=function(){
	var recommend=false;
  if ($("#recommend_no:checked").length==0) {
      recommend=true;
  }; 
  var olm_points="";
  var cee_points="";
  if (recommend) {
    olm_points=$("#olm_points").val();
  }else{
    cee_points=$("#cee_points").val();
  };
    
	var teacherChange={
    "recommend":recommend,
    "competition":olm_points,
    "exam_high":cee_points,
    "prize":$("#prize").val(),
    "description":$("#personal_desc").val(),
    "hobbies":$("#hobbies").val(),
    "cee_province":$("#cee_province").val(),
	};
	remote_save(teacherChange);
};


var submitTeachInfo=function(){
  if(check_form3()==false) return;
	
  var teach_grade=[];
  $("[name=teach-grade]").each(function(index,element){
    if(element.checked==true) {
      teach_grade.push(element.value);
    }
  });

  var teach_subject=[];
  $("[name=subject]").each(function(index,element){
    if(element.checked==true) {
      teach_subject.push(element.value);
    }
  });

  var work_exp=[];
  var teach_exp={
    "time": $("#time").val(),
    "sub": $("#sub").val(),
    "stu": $("#stu").val(),
    "experience": $("#experience").val(),
  };
  if (teach_exp.time!="") {
    work_exp.push(teach_exp);
  };   
	var teacherChange={
    "free_time":free_time.join(""),
    "free_time_desc":$("#timetable").val(),
    "teach_grade":JSON.stringify(teach_grade),
    "teach_subject":JSON.stringify(teach_subject),
    "teach_subject_desc":$("#teach_subject_desc").val(),
    "work_exp":JSON.stringify(work_exp),
  };
	remote_save(teacherChange);
  // @test
  window.location.href = '/teacher/'+teacher_id+'/';
  // window.location.reload();
  // @todo
  // console.log('window');
  // window.location.href = '/teacher/{{ teacher_id }}/';
};